﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RooHui.OA.Biz;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Tool;
using RooHui.OA.Web.Model;
using System.IO;
using System.Drawing;
using RooHui.OA.Biz.Model;

namespace RooHui.OA.Web.Controllers
{
    [HandleError]
    public class ProjectController : Controller
    {
        //
        // GET: /Project/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 分页获取项目信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetProjectListByPage(int page, int pageSize, int productID = -1, int guaranteeCompanyID = -1, int status = -2, string key = "")
        {
            int count = 0;
            var projectList = new List<Project>(); // ProjectBiz.GetProjectListByPage(page, pageSize, productID, guaranteeCompanyID, status, key, ref count);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Rows", projectList);
            dic.Add("Total", count);
            return Content(dic.ToJson());
        }

        public ActionResult ProjectAdd()
        {
            return View();
        }

        /// <summary>
        /// 增加项目
        /// </summary>
        /// <param name="projectModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProjectAdd(ProjectModel projectModel)
        {
            var temp = projectModel.Status == 0 ? "保存" : "提交";
            bool bAddFlag = ProjectBiz.ProjectAdd(projectModel);
            if (bAddFlag)
            {
                return Content(temp + "成功");
            }
            else
            {
                return Content(temp + "失败");
            }
        }

        /// <summary>
        /// 修改页面展示
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult ProjectEdit(int projectId)
        {
            ViewBag.project = ProjectBiz.GetProjectByID(projectId);
            return View();
        }

        /// <summary>
        /// 详情页面展示
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult ProjectDetails(int projectId)
        {
            ViewBag.project = ProjectBiz.GetProjectByID(projectId);
            return View();
        }

        /// <summary>
        /// 修改项目
        /// </summary>
        /// <param name="projectModel"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProjectEdit(ProjectModel projectModel)
        {
            var temp = projectModel.Status == 0 ? "保存" : "提交";
            bool bAddFlag = ProjectBiz.ProjectEdit(projectModel);
            if (bAddFlag)
            {
                return Content(temp + "成功");
            }
            else
            {
                return Content(temp + "失败");
            }
        }

        /// <summary>
        /// 担保公司信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ProjectStatusChange(int projectId, int destinatStatus)
        {
            bool bChangeFlag = ProjectBiz.ProjectStatusChange(projectId, destinatStatus);
            if (bChangeFlag)
            {
                return Content("OK");
            }
            else
            {
                return Content("Failed");
            }
        }
        /// <summary>
        /// add by xiejie
        /// </summary>
        /// <param name="projectID"></param>
        /// <returns></returns>
        public ActionResult ProjectView(int projectID)
        {
            var project = ProjectAuditBiz.GetProjectByIDForAudit(projectID); 
            var processDoingHistoryList = ProcessDoingHistoryBiz.GetProcessDoingHistoryList(projectID);
            var repaymentPlanList = RepaymentPlanBiz.BuildRepaymentPlan(projectID);

            ViewBag.project = project;

            ViewBag.processDoingHistoryList = processDoingHistoryList;
            ViewBag.repaymentPlanList = repaymentPlanList;
            return View();
        }

        #region 上传文件
        public void SWFPrepareUpload()
        {
            try
            {
                if (!System.IO.Directory.Exists(Server.MapPath("/UploadFile/ProResource/temp/")))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath("/UploadFile/ProResource/temp/"));
                }
                var file = Request.Files["Filedata"];
                var img = System.Drawing.Image.FromStream(file.InputStream);
                string filePathName = string.Empty;
                string newFileName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString());
                filePathName = newFileName + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                bool isHorizontal = SaveAndZoom(file, Server.MapPath("~/UploadFile/ProResource/temp/" + filePathName));
                Response.Write("{oldname:'" + file.FileName.Remove(file.FileName.LastIndexOf('.')) + "','name':'" + filePathName + "','path':'/UploadFile/ProResource/temp/" + filePathName + "','horizontal':'" + isHorizontal + "'}");
            }
            catch (Exception e)
            {
                Response.StatusCode = 500;
                Response.Write("");
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="imgs"></param>
        public void SWFUpload(string msg, string imgs)
        {
            string[] img = imgs.Split(';');
            List<SWFUploadItem> items = new List<SWFUploadItem>();
            foreach (var item in img)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    string[] piece = item.Split(',');
                    if (piece.Length != 3)
                    {
                        continue;
                    }
                    string newPath = piece[2].Replace("/UploadFile/ProResource/temp/", "/UploadFile/ProResource/data/");
                    try
                    {
                        if (!System.IO.Directory.Exists(Server.MapPath("/UploadFile/ProResource/data/")))
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath("/UploadFile/ProResource/data/"));
                        }
                        System.IO.File.Copy(Server.MapPath(piece[2]), Server.MapPath(newPath), true);
                        System.IO.File.Delete(Server.MapPath(piece[2]));
                        items.Add(new SWFUploadItem()
                        {
                            name = piece[1],
                            path = newPath,
                            horizontal = piece[0]
                        });
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            Response.Write(items.ToJson());
        }

        /// <summary>  
        /// 图片等比缩放  
        /// </summary>   
        /// <param name="postedFile">原图HttpPostedFile对象</param>  
        /// <param name="savePath">缩略图存放地址</param>  
        public static bool SaveAndZoom(System.Web.HttpPostedFileBase postedFile, string savePath)
        {
            bool isHorizontal = true;
            //创建目录  
            string dir = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            //原始图片（获取原始图片创建对象，并使用流中嵌入的颜色管理信息）  
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

            double zoomHeight = 600;
            double zoomWidth = 800;
            if (initImage.Width < initImage.Height)
            {
                //如果是平的。要求save width:1024 height:768; 
                //否则 width:768 height: 1024
                zoomHeight = 800;
                zoomWidth = 600;
                isHorizontal = false;
            }

            //缩略图宽、高计算  
            double newWidth = initImage.Width;
            double newHeight = initImage.Height;
            //宽大于高或宽等于高（横图或正方）  
            if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
            {
                //如果宽大于模版  
                if (initImage.Width > zoomWidth)
                {
                    //宽按模版，高按比例缩放  
                    newWidth = zoomWidth;
                    newHeight = initImage.Height * (zoomWidth / initImage.Width);
                }
            }
            //高大于宽（竖图）  
            else
            {
                //如果高大于模版  
                if (initImage.Height > zoomHeight)
                {
                    //高按模版，宽按比例缩放  
                    newHeight = zoomHeight;
                    newWidth = initImage.Width * (zoomHeight / initImage.Height);
                }
            }
            //生成新图  
            //新建一个bmp图片  
            System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
            //新建一个画板  
            System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
            //设置质量  
            newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //置背景色  
            newG.Clear(Color.White);
            //画图  
            newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

            //保存缩略图                  
            newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //释放资源  
            newG.Dispose();
            newImage.Dispose();
            initImage.Dispose();
            return isHorizontal;
        }

        #endregion
    }
}
